<template>
  <n-select
    v-model:value="selectedValue"
    :disabled="currentDisabled"
    :placeholder="placeholder"
    :clearable="clearable"
    :multiple="multiple"
    :options="listData"
    :label-field="labelName"
    :value-field="valueName"
    :filterable="filterable"
    :remote="remote"
    @search="remoteMethod"
    @update:value="change"
  />
</template>

<script setup lang="ts">
  import { useVModel } from '@vueuse/core';
  import { computed, inject, onBeforeMount, Ref, ref, PropType } from 'vue';
  const props = defineProps({
    valueName: {
      type: String,
      default: 'id',
    },
    labelName: {
      type: String,
      default: 'name',
    },
    modelValue: {
      type: [String, Number, Boolean, Array],
      default: '',
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: false,
    },
    filterable: {
      type: Boolean,
      default: false,
    },
    remote: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    loadData: {
      type: Function as PropType<Function>,
      required: true,
    },
    isPaging: {
      type: Boolean,
      default: false,
    },
    changeReturnObj: {
      type: Boolean,
      default: false,
    },
  });
  const nForm: any = inject('n-form'); // 使用inject函数注入属性
  const currentDisabled = computed(() => {
    return props.disabled || nForm.props.disabled;
  });
  const emits = defineEmits(['update:modelValue', 'change']);
  const selectedValue = useVModel(props, 'modelValue', emits);
  const loading = ref(false);
  const listData: Ref<any[]> = ref([]);

  onBeforeMount(async () => {
    const result = props.loadData();
    if (
      (typeof result === 'object' || typeof result === 'function') &&
      typeof result.then === 'function'
    ) {
      result.then((res: any) => {
        listData.value = props.isPaging ? res.records : res;
      });
    }
  });

  const remoteMethod = async (query: string) => {
    const result = props.loadData({
      name: query || '',
    });
    if (
      (typeof result === 'object' || typeof result === 'function') &&
      typeof result.then === 'function'
    ) {
      result.then((res: any) => {
        listData.value = props.isPaging ? res.records : res;
      });
    }
  };
  const change = (e) => {
    if (e === null) {
      emits('change', e);
      return;
    }
    if (props.changeReturnObj) {
      listData.value.forEach((item) => {
        if (item[props.valueName] === e) {
          emits('change', item);
        }
      });
    } else {
      emits('change', e);
    }
  };
</script>
